import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:magic_car/common/nodata.dart';
import 'package:magic_car/jiance/faultcode.dart';
import 'package:magic_car/jiance/mileagepage.dart';
import 'package:magic_car/jiance/queryhistoryresult.dart';
import 'package:magic_car/res/colors.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/config.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';

class GroupusePage extends StatefulWidget {
  GroupusePage(this.groupid);

  final String groupid;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<GroupusePage> {
  List items = [
    {
      'title': '月份',
      'select': false,
      'value': '',
      'code': 'online',
      'option': '全部,合格,不合格',
      'type': 1,
      'value_des': ''
    },
    {
      'title': '日期',
      'select': false,
      'value': '',
      'code': 'underline',
      'option': '全部,合格,不合格',
      'type': 2,
      'value_des': ''
    },
    {
      'title': '使用方式',
      'select': false,
      'value': '',
      'code': 'inspector',
      'option': '全部,是,否',
      'type': 3,
      'value_des': '认证检测'
    },
    // {
    //   'title': '站点',
    //   'select': false,
    //   'value': '',
    //   'code': 'site',
    //   'type': 2,
    //   'value_des': ''
    // },
  ];
  String _format = 'yyyy-MMMM';
  String total_num = '0';
  String MIN_DATETIME = '1900-01-01';
  String MAX_DATETIME = '2025-01-01';
  String INIT_DATETIME = '2020-05-01';
  DateTime _dateTime;
  DateTimePickerLocale _locale = DateTimePickerLocale.zh_cn;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  int page = 1;
  String type = "1"; //默认查询认证检测
  List inspecttype = [
    {
      'title': '全车检测',
      'select': false,
      'value': '',
      'code': 'online',
      'option': '全部,合格,不合格',
      'type': 1,
      'value_des': ''
    },
    {
      'title': '事故检测',
      'select': false,
      'value': '',
      'code': 'underline',
      'option': '全部,合格,不合格',
      'type': 2,
      'value_des': ''
    },
    {
      'title': '金融检测',
      'select': false,
      'value': '',
      'code': 'inspector',
      'option': '全部,是,否',
      'type': 3,
      'value_des': ''
    },
    {
      'title': '保修检测',
      'select': false,
      'value': '',
      'code': 'inspector',
      'option': '全部,是,否',
      'type': 3,
      'value_des': ''
    },
    {
      'title': '认证检测',
      'select': false,
      'value': '',
      'code': 'inspector',
      'option': '全部,是,否',
      'type': 3,
      'value_des': ''
    },
  ];
  List usetype = ['认证检测', '数据查询', '质保产品'];
  ScrollController _scrollController = new ScrollController();
  List querydata = [];
  List orderdata = [];

  initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        // loadMore();
        loaddata();
      }
    });
    // formList = [];
    loaddata();
  }

  showPicker(BuildContext context) {
    Picker picker = Picker(
        adapter: PickerDataAdapter<String>(pickerdata: usetype),
        changeToFirst: false,
        textAlign: TextAlign.left,
        textStyle: TextStyle(color: Colors.blue),
        selectedTextStyle: TextStyle(color: Colors.red),
        columnPadding: const EdgeInsets.all(8.0),
        confirmText: '确定',
        confirmTextStyle: TextStyle(color: Colors.black),
        cancelText: '取消',
        cancelTextStyle: TextStyle(color: Colors.black),
        onConfirm: (Picker picker, List value) {
          print(value.toString());
          print(picker.getSelectedValues());
          // formList[3]['value'] = picker.getSelectedValues()[0];
          // setState(() {
          //   formList = formList;
          // });
          // type_index = value[0];
          // type_index = i;
          setState(() {
            type = (value[0] + 1).toString();
            page = 1;
            items[2]['value_des'] = usetype[value[0]];
          });
          loaddata();
        });

    picker.show(_scaffoldKey.currentState);
  }

  //获取套餐使用记录
  loaddata() async {
    EasyLoading.show(status: "加载中...");
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["uid"] = pref.getString('uid');
    map["page"] = page.toString();
    map['id'] = widget.groupid;
    map['type'] = type;
    map["month"] = items[0]['value'];
    map["day"] = items[1]['value'];
    print("参数${map}");
    HttpHelper.post(HttpHelper.API_BussinessGroupUseRec, (data) async {
      EasyLoading.dismiss();
      //loadpage.close();
      if (data != null) {
        print(data);
        if (data["code"].toString() == "1") {
          setState(() {
            // total_money = data['info']['total'] != null
            //     ? data['info']['total'].toString()
            //     : "0.00";
            //formList = data["info"];
            // acountinfo = data["info"];
          });
          if (page == 1) {
            if (type == "2") {
              //查询数据
              querydata = [];
            } else {
              //订单数据
              orderdata = [];
            }
          }
          if (data["info"].length > 0) {
            if (type == "2") {
              querydata.addAll(data['info']);
              setState(() {
                querydata = querydata;
              });
            } else {
              orderdata.addAll(data["info"]);
              setState(() {
                orderdata = orderdata;
              });
            }
            if (data["info"].length >9) {
              page++;
            }
          } else {
            Toast.show('无相关数据', context);
          }
        }
      }
    }, params: map);
  }

  void _showDatePicker(item) {
    print('选择日期');
    DatePicker.showDatePicker(
      context,
      onMonthChangeStartWithFirstDate: true,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        confirm: Text('确定', style: TextStyle(color: Colors.red)),
        cancel: Text('不限', style: TextStyle(color: Colors.cyan)),
      ),
      minDateTime: DateTime.parse(MIN_DATETIME),
      // maxDateTime: DateTime.parse(MAX_DATETIME),
      initialDateTime: _dateTime,
      dateFormat: _format,
      locale: _locale,
      onClose: () => print("----- onClose -----"),
      onCancel: () {
        //不限
        setState(() {
          item['value_des'] = item['type'] == 1 ? '月份' : '日期';
          item['value'] = '';
          item['select'] = false;
        });
        page = 1;
        // // type = 3;
        loaddata();
      },
      onChange: (dateTime, List<int> index) {
        print(dateTime);
        setState(() {
          //_dateTime = dateTime;
        });
      },
      onConfirm: (dateTime, List<int> index) {
        print(dateTime);
        print(item);
        setState(() {
          //  String code = item["code"];
          if (item['type'] == 2) {
            item["value"] = formatDate(dateTime, [yyyy, "-", mm, '-', dd]);

            item['value_des'] = formatDate(dateTime, [yyyy, "-", mm, '-', dd]);
          } else {
            item["value"] = formatDate(dateTime, [yyyy, "-", mm]);

            item['value_des'] = formatDate(dateTime, [yyyy, "-", mm]);
          }

          for (int i = 0; i < items.length - 1; i++) {
            if (item != items[i]) {
              items[i]['select'] = false;
              items[i]['value'] = "";
              items[i]['value_des'] = i == 0 ? '月份' : '日期';
            }
          }
          item['select'] = true;
          // item['value']=dateTime;
          //formalities[code] = item["value"];
        });
        setState(() {
          // _dateTime = dateTime;
        });
        page = 1;
        // type = 3;
        loaddata();
        //saveResult();
      },
    );
  }

  Widget filter() {
    List<Widget> tiles = [];
    Widget content;

    for (var i = 0; i < items.length; i++) {
      var radios = items[i]['title'];
      bool checkvalue = false;

      //  bool has = RegExp(item['value']).hasMatch(radios);
      if (radios != "") {
        tiles.add(Padding(
            padding: new EdgeInsets.fromLTRB(10, 5, 0, 5),
            child: GestureDetector(
                // key: _myKey,
                onTap: () {
                  if (items[i]['type'] == 2 || items[i]['type'] == 1) {
                    if (items[i]['type'] == 2) {
                      _format = 'yyyy-MMMM-dd';
                    } else {
                      _format = 'yyyy-MMMM';
                    }
                    _showDatePicker(items[i]);
                  } else {
                    print('选择使用方式');
                    showPicker(context);
                    //  showtypeView();
                    //showSiteView();
                  }

                  //showSiteView();
                },
                child: Container(
                  width: 100,
                  padding: EdgeInsets.symmetric(vertical: 8, horizontal: 7),
                  child: Center(
                      child: Text(
                    items[i]['value_des'] == ""
                        ? radios
                        : items[i]['value_des'],
                    style: new TextStyle(
                        fontSize: 10,
                        color: items[i]['select'] == false
                            ? Color.fromRGBO(120, 120, 120, 1)
                            : Colors.white),
                  )),
                  decoration: new BoxDecoration(
                    color: items[i]['select'] == false
                        ? Color.fromRGBO(235, 235, 235, 1)
                        : Colors.blue,
                    borderRadius:
                        new BorderRadius.all(new Radius.circular(5.0)),
                  ),
                ))));
      }

      // tiles.add(

    }
    content = new Container(
        child: new Wrap(
      spacing: 0,
      runSpacing: 0,
      children: tiles,
    ));
    return content;
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.white,
        titleSpacing: 0,
        title: Text(
          '使用记录',
          style: TextStyle(fontSize: Config.title_size),
        ),
      ),
      body: Stack(
        children: [
          Padding(padding: EdgeInsets.fromLTRB(0, 10, 10, 5), child: filter()),
          Container(
              margin: EdgeInsets.fromLTRB(10, 50, 10, 0),
              child:
                  // type=="2" && querydata.length==0?Nodata():
                  ListView.builder(
                      controller: _scrollController,
                      itemCount:
                          type == "2" ? querydata.length : orderdata.length,
                      itemBuilder: (BuildContext context, int index) {
                        if (type == "2") {
                          return queryitem(querydata[index]);
                        } else {
                          return orderitem(orderdata[index]);
                        }
                        //type=="2"?queryitem(querydata[index]):orderitem(orderdata[index]);
                      }))
        ],
      ),
    );
  }

  Widget orderitem(data) {
    return Container(
      padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
      margin: EdgeInsets.fromLTRB(0, 5, 0, 0),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '订单号：${data['order_sn']}',
            style: TextStyle(fontWeight: FontWeight.w700),
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(0, 5, 0, 0),
            child: Text(
              "类型：${data['test_type']}",
              style: TextStyle(color: Colors.black),
            ),
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(0, 5, 0, 0),
            child: Text(
              "价格：¥${data['orderPrice']}",
              style: TextStyle(color: Colours.bj_red_r1),
            ),
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
            child: Text(
              "${data['overtime']}",
              style: TextStyle(color: Colours.text_gray, fontSize: 13),
            ),
          ),
        ],
      ),
    );
  }

  queryresult(id) async {
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["uid"] = pref.getString('uid');
    map["id"] = id;
    HttpHelper.post(HttpHelper.API_Requerydata, (data) async {
      if (data != null) {
        print(data);
        if (data["code"].toString() == "1") {
          var querytype = int.parse(data["info"]['query_type']);
          if (querytype == 2) {
            //历史里程
            if (data["info"].containsKey('use_url') &&
                data["info"]['use_url'].toString() == "1") {
              Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                return new QueryReusltPage(
                    data['info']['id'], data['info']['result_url']);
              }));
            } else {
              Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                return new MileAgePage(data['info']['id']);
              }));
            }
          } else if (querytype == 1) {
            //历史故障码
            if (data["info"].containsKey('use_url') &&
                data["info"]['use_url'].toString() == "1") {
              Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                return new QueryReusltPage(
                    data['info']['id'], data['info']['result_url']);
              }));
            } else {
              Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                return new FaultCodePage(data['info']['id']);
              }));
            }
          } else {
            //维保和碰撞需要异步获取结果

            Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
              return new QueryReusltPage("", data['info']['result_url']);
            }));

            //  Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
            //     return new QueryReusltPage(data['info']['id']);
            //   }));
          }
        } else {
          Toast.show(data['msg'], context);
        }
      }
    }, params: map);
  }

  Widget queryitem(data) {
    return Container(
      padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
      margin: EdgeInsets.fromLTRB(0, 5, 0, 0),
      color: Colors.white,
      child: InkWell(
          onTap: () {
            queryresult('${data['id']}');
          },
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '车架号：${data['vin']}',
                style: TextStyle(fontWeight: FontWeight.w700),
              ),
              Padding(
                padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
                child: Text(
                  "价格：¥${data['price']}",
                  style: TextStyle(color: Colours.bj_red_r2),
                ),
              ),
              //query_type_str
              Padding(
                padding: EdgeInsets.fromLTRB(0, 0, 0, 5),
                child: Text(
                  "查询类型：${data['query_type_str']}",
                  style: TextStyle(color: Colors.black),
                ),
              ),
              Text(
                '${data['updatetime']}',
                style: TextStyle(fontSize: 13, color: Colours.text_gray),
              )
            ],
          )),
    );
  }
}
